<template>
  <div class="page-container">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>自动化营销</el-breadcrumb-item>
        <el-breadcrumb-item>用户旅程管理</el-breadcrumb-item>
        <el-breadcrumb-item>查看用户旅程</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <p class="font22 mb60">查看用户旅程</p>
    <!-- 营销目的 -->
    <p class="common-style t_l w100 mb30" >
      <span style="color:red">*</span>
      <span class="label font16 color333">营销目的：</span>
      <span v-if="tripInfo.tripType == '1'" class="value font16 color333">拉新</span>
      <span v-else-if="tripInfo.tripType == '2'" class="value font16 color333">促活</span>
      <span v-else-if="tripInfo.tripType == '3'" class="value font16 color333">留存</span>
      <span v-else-if="tripInfo.tripType == '4'" class="value font16 color333">转化消费</span>
      <span v-else-if="tripInfo.tripType == '5'" class="value font16 color333">分享传播</span>
    </p>

    <!-- 营销目的 -->
    <p class="common-style t_l w100 mb30">
      <span style="color:red">*</span>
      <span class="label font16 color333">营销名称：</span>
      <span class="value">{{tripInfo.tripName}}</span>
    </p>

    <!-- 营销目的 -->
    <p class="common-style t_l w100 mb30">
      <span style="color:red">*</span>
      <span class="label font16 color333">营销时间：</span>
      <span v-if="tripInfo.timeType == '2'" class="value font16 color333">无固定时间</span>
      <span v-else class="value">
        <span><el-radio disabled></el-radio>固定时间段</span>
        <span class="m_l10">{{ tripInfo.startTime }} - {{ tripInfo.endTime }}</span>
      </span>
    </p>

  <!--用户旅程表格 -->
    <div class="w100 t_l f_l">
      <span style="color:red">*</span>
      <span class="label font16 color333">用户旅程：</span>
    </div>
      <!-- 用户旅程表格样式 -->
      <div v-if="easyFlowVisible" style="height: calc(70vh)" class="ml90 border mb60">
        <div style="display: flex;height: calc(100% - 47px);width:100%">
            <!-- 中间画图部分 -->
            <div id="efContainer" ref="efContainer" class="container">
                <template v-for="node in data.nodeList">
                    <flow-node
                      :id="node.id"
                      :key="node.id"
                      :node="node"
                      :showDelete="showDelete"
                      :showAdd="showAdd"
                      :activeElement="activeElement"
                      @clickNode="clickNode(node)"
                      @setting="setting(node)"
                    >
                    </flow-node>
                </template>
            </div>
        </div>
      </div>

      <!-- 设置弹窗内容 -->
      <el-dialog
        :visible.sync="showSettings"
        v-if="showSettings"
        :close-on-click-modal="false"
        :before-close="handleClose"
        :class="{longDialog:isLong,middleDialog:isMiddle,shortDialog:isShort,shortDialogPadding:isShort}" 
        >

        <userGroupSelectionInfo v-if="templateCode == 'user_group_selection_node'" :node-info="currentNode"  @handleClose="handleClose"></userGroupSelectionInfo>
        <eventSelectionInfo v-if="templateCode == 'event_selection_node'" :node-info="currentNode" @handleClose="handleClose"></eventSelectionInfo>
        <eventJudgeInfo v-if="templateCode == 'event_judge_node'" :node-info="currentNode" @handleClose="handleClose"></eventJudgeInfo>
        <sendCouponInfo v-if="templateCode == 'send_coupon_node'" :nodeInfo="currentNode" @handleClose="handleClose"/>
        <sendRedEnvelepelInfo v-if="templateCode == 'send_red_envelope_node'" :node-info="currentNode" @handleClose="handleClose"/>
        <sendMarketInfo v-if="templateCode == 'send_market_node'" :node-info="currentNode"  @handleClose="handleClose"/>
        <sendSmsInfo v-if="templateCode == 'send_sms_node'" :node-info="currentNode" @handleClose="handleClose"/>
        <sendMailInfo v-if="templateCode == 'send_mail_node'" :node-info="currentNode" @handleClose="handleClose"/>
        <sendGoodsInfo v-if="templateCode == 'send_goods_node'" :node-info="currentNode"  @handleClose="handleClose"/>
        <waitInfo v-if="templateCode == 'wait_node'" :node-info="currentNode"  @handleClose="handleClose"/>
        <timeTriggerInfo v-if="templateCode == 'timed_trigger_node'" :node-info="currentNode" @handleClose="handleClose"/>
        <labelSelectionInfo v-if="templateCode == 'label_selection_node'" :node-info="currentNode"  @handleClose="handleClose"></labelSelectionInfo>
      </el-dialog>
    

    <!-- 确认按钮 -->
    <div class="button-wrap">
      <el-button class="searchButton" size="small" @click="goBack()">确认</el-button>
    </div>

  </div>
</template>
<script>
    import '@/components/AutoMarket/setPath/jsplumb';
    import { easyFlowMixin } from '@/components/AutoMarket/setPath/mixins';
    import flowNode from '@/components/AutoMarket/setPath/node';
    import lodash from 'lodash';

    import waitInfo from "@/components/AutoMarket/tripView/waitInfo";
    import labelSelectionInfo from '@/components/AutoMarket/tripView/labelSelectionInfo';
    import eventJudgeInfo from "@/components/AutoMarket/tripView/eventJudgeInfo";
    import eventSelectionInfo from "@/components/AutoMarket/tripView/eventSelectionInfo";
    import sendAppPushInfo from "@/components/AutoMarket/tripView/sendAppPushInfo";
    import sendCouponInfo from "@/components/AutoMarket/tripView/sendCouponInfo";
    import sendGoodsInfo from "@/components/AutoMarket/tripView/sendGoodsInfo";
    import sendGraphicInfo from "@/components/AutoMarket/tripView/sendGraphicInfo";
    import sendMailInfo from "@/components/AutoMarket/tripView/sendMailInfo";
    import sendMarketInfo from "@/components/AutoMarket/tripView/sendMarketInfo";
    import sendRedEnvelepelInfo from "@/components/AutoMarket/tripView/sendRedEnvelopeInfo";
    import sendSmsInfo from "@/components/AutoMarket/tripView/sendSmsInfo";
    import sendWechatInfo from "@/components/AutoMarket/tripView/sendWechatInfo";
    import timeTriggerInfo from "@/components/AutoMarket/tripView/timeTriggerInfo";
    import timedTriggerInfo from "@/components/AutoMarket/tripView/timedTriggerInfo";
    import userGroupSelectionInfo from "@/components/AutoMarket/tripView/userGroupSelectionInfo";



    export default {
      computed: {
        mainTabs: {
          get() {
            return this.$store.state.tab.mainTabs;
          },
          set(val) {
            this.$store.commit("updateMainTabs", val);
          }
        },
        mainTabsActiveName: {
          get() {
            return this.$store.state.tab.mainTabsActiveName;
          },
          set(val) {
            this.$store.commit("updateMainTabsActiveName", val);
          }
        }
      },
      data() {
        return {
          jsPlumb: null,
          easyFlowVisible: true,
          flowInfoVisible: true,
          loadEasyFlowFinish: false,
          data: {},
          activeElement: {
            type: undefined,
            nodeId: undefined,
            sourceId: undefined,
            targetId: undefined
          },
          showDelete: false,                   // 是否显示左上角删除按钮
          showAdd: false,                      // 是否显示右上角设置按钮
          tripId: '',                          // 旅程ID
          tripInfo: {},                        // 旅程信息
          showSettings: false,                 // 是否显示设置弹窗内容
          currentNode: {},                     // 点击编辑时该标签的数据信息
          templateCode: '',                    // 选中节点模板code
          isLong:false,                        // 弹框宽度(大)
          isMiddle:false,                      // 弹框宽度（中）
          isShort:false,                       // 弹框宽度（小）
        }
      },
      // 一些基础配置移动该文件中
      mixins: [easyFlowMixin],
      components: {
        flowNode,waitInfo,labelSelectionInfo,eventJudgeInfo,eventSelectionInfo,sendAppPushInfo,sendCouponInfo,sendGoodsInfo,sendGraphicInfo,sendMailInfo,sendMarketInfo,sendRedEnvelepelInfo,sendSmsInfo,sendSmsInfo,
        sendWechatInfo,timeTriggerInfo,timedTriggerInfo,userGroupSelectionInfo
      },

        mounted() {
          
          let that = this;
            
            that.jsPlumb = jsPlumb.getInstance();

            that.$nextTick(() => {
              // 默认加载流程A的数据、在这里可以根据具体的业务返回符合流程数据格式的数据即可
              // 获取旅程列表带来的旅程ID   getTripDetailAndNodeList
              if(that.$route.query.id && that.$route.query.id != '') {
                that.tripId = that.$route.query.id;
                let params = {
                  tripId: that.tripId,
                  actionType:2
                }
                that.utils.request.getTripDetailAndNodeList(params,function(res) {
                    if(res.data) {
                      that.tripInfo = res.data;
                      // 旅程流程图赋值
                      let nodeList = that.tripInfo.tripBranchNodeDetailResponseList;
                      // let originalLists = JSON.parse(that.tripInfo.lineList);
                      let originalLists = that.tripInfo.lineList;

                      // 封装数据进行匹配插件
                      nodeList.forEach((item) => {
                        item.id = item.nodeId;
                        item.templateCode = item.nodeTemplateCode;
                      })
                      that.data.nodeList = nodeList;
                      that.data.lineList = originalLists;
                      // 初始化流程图
                      that.dataReload(that.data);
                    }
                })
              }
            })
        },
        methods: {

          // 关闭设置弹窗
          handleClose() {
            this.showSettings = false;
          },

          // 点击元素
          clickNode() {

          },

          // 点击设置事件传递
          setting(node) {
            this.currentNode = node;
            this.templateCode = node.templateCode;
            if(this.templateCode == 'wait_node' || this.templateCode == 'timed_trigger_node'){
              this.isShort = true;
              this.isMiddle = false;
              this.isLong = false;
            }else if(this.templateCode == 'event_selection_node' || this.templateCode == 'user_group_selection_node'||this.templateCode == 'event_judge_node'||this.templateCode == 'send_sms_node'||this.templateCode == 'send_mail_node'){
              this.isShort = false;
              this.isMiddle = true;
              this.isLong = false;
            }else if(this.templateCode == 'label_selection_node'||this.templateCode == 'send_coupon_node'||this.templateCode == 'send_red_envelope_node'||this.templateCode == 'send_market_node'||this.templateCode == 'send_goods_node'){
              this.isShort = false;
              this.isMiddle = false;
              this.isLong = true;
            }
            this.showSettings = true;
          },

          // tabs, 删除tab
          removeTabHandle(tabName) {
            this.mainTabs = this.mainTabs.filter(item => item.name !== tabName);
            if (this.mainTabs.length >= 1) {
              // 当前选中tab被删除
              if (tabName === this.mainTabsActiveName) {
                this.$router.push(
                  { path: '/Pages/AutoMarket/UserJourneyManagement/UserJourneyManagement' }, () => {
                    this.mainTabsActiveName = this.$route.name;
                  }
                );
              }
            } else {
              this.$router.push(
                { path: '/Pages/AutoMarket/UserJourneyManagement/UserJourneyManagement'},() => {
                  this.mainTabsActiveName = this.$route.name;
                }
              );
            }
          },
          // 点击确定返回旅程列表
          goBack() {
            this.removeTabHandle(this.mainTabsActiveName);
          },

          // 返回唯一标识
          getUUID() {
            return Math.random().toString(36).substr(3, 10)
          },

            // 初始化方法
            jsPlumbInit() {
              
              this.jsPlumb.ready(() => {
                this.jsPlumb.importDefaults(this.jsplumbSetting)
                this.jsPlumb.setSuspendDrawing(false, true);
                this.loadEasyFlow();
                
                this.jsPlumb.bind('click', (conn, originalEvent) => {
                  this.activeElement.type = 'line'
                  this.activeElement.sourceId = conn.sourceId
                  this.activeElement.targetId = conn.targetId
                  this.$refs.nodeForm.lineInit({
                    from: conn.sourceId,
                    to: conn.targetId,
                    label: conn.getLabel()
                  })
                })

                // 连线
                this.jsPlumb.bind("connection", (evt) => {
                  let from = evt.source.id
                  let to = evt.target.id
                  if (this.loadEasyFlowFinish) {
                    this.data.lineList.push({from: from, to: to})
                  }
                })

                // 改变线的连接节点
                this.jsPlumb.bind("connectionMoved", (evt) => {
                  this.changeLine(evt.originalSourceId, evt.originalTargetId)
                })

                // 连线右击
                this.jsPlumb.bind("contextmenu", (evt) => {
                  // 
                })

                // 连线
                this.jsPlumb.bind("beforeDrop", (evt) => {
                  return;
                  let from = evt.sourceId;
                  let to = evt.targetId;
                  if (from === to) {
                    this.$message.error('节点不支持连接自己');
                    return false;
                  }
                  if (this.hasLine(from, to)) {
                    this.$message.error('该关系已存在,不允许重复创建');
                    return false;
                  }
                  if (this.hashOppositeLine(from, to)) {
                    this.$message.error('不支持两个节点之间连线回环');
                    return false;
                  }
                  this.$message.success('连接成功');
                  return true;
                })

                // beforeDetach
                this.jsPlumb.bind("beforeDetach", (evt) => {
                  // 
                })
                this.jsPlumb.setContainer(this.$refs.efContainer)
              })
            },

            // 加载流程图
            loadEasyFlow() {
              // 初始化节点
              for (var i = 0; i < this.data.nodeList.length; i++) {
                let node = this.data.nodeList[i]
                // 设置源点，可以拖出线连接其他节点
                this.jsPlumb.makeSource(node.id, this.jsplumbSourceOptions)
                // // 设置目标点，其他源点拖出的线可以连接该节点
                this.jsPlumb.makeTarget(node.id, this.jsplumbTargetOptions)
              }
              // 初始化连线
              for (var i = 0; i < this.data.lineList.length; i++) {
                let line = this.data.lineList[i]
                this.jsPlumb.connect({source: line.from, target: line.to, label: line.label ? line.label : ''}, this.jsplumbConnectOptions)
              }
              this.$nextTick(function () {
                this.loadEasyFlowFinish = true
              })
            },

            setLineLabel(from, to, label) {
              var conn = this.jsPlumb.getConnections({
                  source: from,
                  target: to
              })[0]
              if (!label || label === '') {
                conn.removeClass('flowLabel')
                conn.addClass('emptyFlowLabel')
              } else {
                conn.addClass('flowLabel')
              }
              conn.setLabel({
                label: label,
              })
              this.data.lineList.forEach(function (line) {
                if (line.from == from && line.to == to) {
                  line.label = label
                }
              })
            },

          // 是否具有该线
          hasLine(from, to) {
            for (var i = 0; i < this.data.lineList.length; i++) {
              var line = this.data.lineList[i]
              if (line.from === from && line.to === to) {
                return true
              }
            }
            return false
          },

          // 是否含有相反的线
          hashOppositeLine(from, to) {
            return this.hasLine(to, from)
          },

          // 加载流程图
          dataReload(data) {
            // 
            this.easyFlowVisible = false
            // this.data.nodeList = []
            // this.data.lineList = []
            this.$nextTick(() => {
              data = lodash.cloneDeep(data);
              // 
              this.easyFlowVisible = true
              this.data = data
              this.$nextTick(() => {
                this.jsPlumb = jsPlumb.getInstance()
                this.$nextTick(() => {
                  this.jsPlumbInit()
                })
              })
            })
          },
        }
    }
</script>
<style lang="scss" scoped>
.ml90{
  margin-left: 90px;
}
.border{
  border: 1px solid #e7e7e7;
}
#efContainer {
  border-top: 0 none;
}

/* 弹窗样式部分 */ 
.longDialog{
  /deep/ .el-dialog{
    width: 1254px !important;
  }
}
.middleDialog{
  /deep/ .el-dialog{
    width: 922px !important;
  }
}
.shortDialog{
  /deep/ .el-dialog{
    width: 610px !important;
  }
}
.shortDialogPadding{
  /deep/ .el-dialog{
    .el-dialog__body{
      padding: 0 90px !important;
    }
  }
}
.btns {
  margin-bottom: 30px;
  margin-top: 30px;
  border-top: 1px solid #e7e7e7;
  padding-top: 30px;
}
</style>

